import UnityPy

path_id_map = {}

obj_name_list = [
    "dlg_indx",
    "dlg_text",
]


def gen_path_id_map(env: any):
    for obj in env.objects:
        if obj.type.name == "ResourceManager":
            rm = obj.read()
            for container, ptr in rm.m_Container.items():
                try:
                    data = ptr.read()
                    path_id = data.path_id
                    if len(container.split("/")[-2:]) < 2:
                        continue
                    _lang, _obj_name = container.split("/")[-2:]
                    if _lang == "ja-jp" and _obj_name in obj_name_list:
                        path_id_map[path_id] = (
                            _obj_name.split("_")[0].upper()
                            + "_"
                            + _obj_name.split("_")[1].capitalize()
                        )
                except Exception:
                    ...
            break


def extract_file(src, dst):
    env = UnityPy.load(src)
    gen_path_id_map(env)
    print(path_id_map)
    for obj in env.objects:
        if obj.type.name == "TextAsset" and obj.path_id in path_id_map.keys():
            obj_name: str = path_id_map[obj.path_id]
            if not obj_name.startswith("DLG"):
                continue  # noqa 过滤掉非DLG文件
            print(obj_name)
            data = obj.read()

            with open(f"{dst}/{obj_name}", "wb") as f:
                f.write(bytes(data.script))


extract_file("data/data.unity3d", "output/提取自data.unity3d")
